package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.order.dto.OrderItemResponse;
import com.mall.order.dto.PayOrderSuccessRequest;
import com.mall.order.dto.PayOrderSuccessResponse;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.IUserService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.UserLoginResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

@Service
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference(check = false)
    OrderCoreService orderCoreService;

    @Autowired
    PaymentMapper mapper;

    @Reference(check = false)
    IUserService userService;

    /*
         获取支付二维码
     */
    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();
        // 1. 调用当面付Demo中的test_precreate方法，获取支付二维码
        String codeFileName = payHelper.test_trade_precreate(request);

        // 2. 判斷二维码是否获取成功
        if (codeFileName == null) {
            // 获取支付二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        // 获取支付二维码成功
        // 1. 要在tb_payment插入一条记录，记录订单的支付信息， PayResultEnum.PAY_PROCESSING（支付处理中）

        Payment payment = new Payment();
        @NotNull(message = "userId不可为空") Long userId = request.getUserId();
        payment.setPayerUid(userId);
        payment.setPayerAmount(request.getTotalFee());
        payment.setOrderAmount(request.getOrderFee());
        payment.setStatus(PayResultEnum.PAY_PROCESSING.getCode());
        payment.setCreateTime(new Date());
        payment.setPayWay(request.getPayChannel());
//        payment.setProductName(request.getSubject());
        @NotBlank(message = "tradeNo不可为空") String orderId = request.getTradeNo();
        payment.setOrderId(orderId);
        UserLoginResponse user = userService.getUserById(userId);
        payment.setPayerName(user.getUsername());

        //插入支付表,支付逻辑是一个商品插入一次表
        //先用订单号,找到所有的商品,有几个商品插入几个记录
      List<OrderItemResponse> orderItems = orderCoreService.getAllItem(orderId);
        for (OrderItemResponse orderItem : orderItems) {
            String title = orderItem.getTitle();
            payment.setProductName(title);
            payment.setPayerAmount(orderItem.getPrice());
                mapper.insertSelective(payment);
        }

        // 2. 返回二维码，并设置响应结果信息
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(codeFileName);
        return alipaymentResponse;
    }

    /*
           查询订单的支付结果
     */
    @Override
    public AlipayQueryRetResponse queryAlipayRet(String orderId) {
        AlipayQueryRetResponse alipayQueryRetResponse = new AlipayQueryRetResponse();
        // 调用test_trade_query方法，查询指定的订单支付结果
//        PaymentRequest request = new PaymentRequest();
//        request.setTradeNo(orderId);

        boolean paySuccess = payHelper.test_trade_query(orderId);
//         String orderId = request.getTradeNo();
        // 判断是否支付成功
        // TODO: 2021/12/17  
        if (paySuccess) {
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_SUCCESS
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            Payment payment = new Payment();
            payment.setPaySuccessTime(new Date());
            payment.setUpdateTime(new Date());
            payment.setCompleteTime(new Date());
            // TODO: 2021/12/16
            payment.setStatus(PayResultEnum.PAY_SUCCESS.getCode());
            int rows = mapper.updateByExampleSelective(payment, example);

            PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
            payOrderSuccessRequest.setOrderId(orderId);
////            调用方法更新库存等等
            //  调用订单服务，完成以下功能
            PayOrderSuccessResponse payOrderSuccessResponse = orderCoreService.payOrderSuccess(payOrderSuccessRequest);
            if (!payOrderSuccessResponse.getCode().equalsIgnoreCase(SysRetCodeConstants.SUCCESS.getCode())){
                //说明更新订单状态，更新锁定库存失败了
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
                return alipayQueryRetResponse;
            }


            // 2. 修改订单的状态为已支付
            // 3. 修改库存，根据OrderId，查询出所有的订单商品条目，根据每一个商品的数量，扣减锁定库存
        } else {
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_FAIL
            Payment payment = new Payment();
            payment.setStatus(PayResultEnum.PAY_FAIL.getCode());
            mapper.updateByExampleSelective(payment,example);
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getMsg());
            // 返回相应的response
            return alipayQueryRetResponse;

        }
        alipayQueryRetResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipayQueryRetResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());

        // 返回相应的response
        return alipayQueryRetResponse;
    }
}
